package com.stedu.mall.orderservice.controller;

import com.github.pagehelper.PageInfo;
import com.stedu.mall.common.bean.Order;
import com.stedu.mall.common.bean.OrderVo;
import com.stedu.mall.common.bean.RespBean;
import com.stedu.mall.common.exception.SteduException;
import com.stedu.mall.common.service.OrederService;
import com.stedu.mall.common.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrederService orderService;

    @PostMapping
    public RespBean insert(@RequestBody OrderVo orderVo,@RequestHeader("token") String token) throws SteduException {
        //解析token获取用户id
        Map<String, Object>map= JwtUtil.parseJwtToMap(token);
        Integer userId=(Integer) map.get("id");

        orderVo.setUserId(userId);
        //添加订单
        orderService.insert(orderVo);
        return RespBean.ok("添加订单成功",orderVo);
    }

    @GetMapping("/{id}")
    public RespBean selectById(@PathVariable("id") String id , @RequestHeader("token") String token) throws SteduException {
        Map<String, Object>map= JwtUtil.parseJwtToMap(token);
        Integer userId=(Integer) map.get("id");
        Order order = orderService.selectById(id, userId);

        return RespBean.ok("查询成功",order);
    }

    @PostMapping("/pay")
    public RespBean pay(@RequestBody OrderVo orderVo,@RequestHeader("token") String token) throws SteduException {
        Map<String, Object>map= JwtUtil.parseJwtToMap(token);
        Integer userId=(Integer) map.get("id");
        orderVo.setUserId(userId);

        orderService.pay(orderVo);
        return RespBean.ok("支付成功");

    }
    @GetMapping("/user")
    public RespBean selectByUser(Integer pageNum, Integer pageSize,@RequestHeader("token") String token) throws SteduException {
        Map<String, Object>map= JwtUtil.parseJwtToMap(token);
        Integer userId=(Integer) map.get("id");
        Order condition=new Order();
        condition.setUserId(userId);

        PageInfo<Order> pageInfo = orderService.selectByCondition(condition, pageNum, pageSize);
        return  RespBean.ok("查询成功",pageInfo);
    }
    @GetMapping("/All")
     public RespBean selectByUserAll(Integer pageNum, Integer pageSize){
        Order condition=new Order();
        PageInfo<Order> pageInfo = orderService.selectByCondition2(condition, pageNum, pageSize);
        return  RespBean.ok("查询成功",pageInfo);
    }
    @PutMapping("/{id}")
    public RespBean update(@PathVariable("id")String id) throws SteduException {
        Order order = orderService.selectOneById(id);
       int  i= orderService.updatestatus(order);
       if(i==2){
            return RespBean.ok("成功发货");
        }
           return RespBean.ok("成功收获");
    }
    }
